const {ccclass, property} = cc._decorator;

type heroState = {
    stand: number,
    attck: number
}


@ccclass
export default class NewClass extends cc.Component {

    // LIFE-CYCLE CALLBACKS:
    // 当前状态
    private State:heroState = {
        stand: 1,
        attck: 2
    }
    // 人物速度
    @property(cc.Integer)
    speed:number = 0;
    // 键盘按下或抬起
    private Input:{} = { };
    // 给物理引擎设置方向
    lv:cc.Vec2 = cc.v2(0, 0);
    // 人物方向
    sp:cc.Vec2 = cc.v2(0, 0);

    // 动画
    private curAni:string = '';
    aniHero:cc.Animation

    onLoad () {
        // 初始化键盘输入监听
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this); 
        // 动画
        this.aniHero = this.node.getComponent(cc.Animation);
        
    }

    // 键盘按下事件
    onKeyDown(event: cc.Event.EventKeyboard) {
        this.Input[event.keyCode] = 1;
        let keyCode = event.keyCode;

        this.moveDirect();
    }
    // 键盘抬起事件
    onKeyUp(event: cc.Event.EventKeyboard) {
        this.Input[event.keyCode] = 0;

        this.sp = cc.v2(0, 0);
    }
    // 设置人物动画
    setAni(anima:string) {
        if (this.curAni == anima) return;
        this.curAni = anima;
        this.aniHero.play(this.curAni);
    }

    // moveDirect 移动判断
    moveDirect() {
        if (cc.find('Canvas/dialog').active) return ;

        if (this.Input[cc.macro.KEY.a] || this.Input[cc.macro.KEY.left]) {
            // this.node.x -= this.speed * dt;
            this.setAni("Left");
            this.sp.x = -1;
        } else if (this.Input[cc.macro.KEY.d] || this.Input[cc.macro.KEY.right]) { 
            // this.node.x += this.speed * dt;
            this.setAni("Right");
            this.sp.x = 1;
        } else if (this.Input[cc.macro.KEY.w] || this.Input[cc.macro.KEY.up]) { 
            // this.node.y += this.speed * dt;
            this.setAni("Up")
            this.sp.y = 1;
        } else if (this.Input[cc.macro.KEY.s] || this.Input[cc.macro.KEY.down]) { 
            // this.node.y -= this.speed * dt;
            this.setAni("Down");
            this.sp.y = -1;
        }
    }

    update (dt) {
        // 添加物理碰撞引擎后，不能通过改变坐标来使人物移动，需要通过改变线性速度
        this.lv = this.node.getComponent(cc.RigidBody).linearVelocity;
        
        if (this.sp.x != 0) {
            this.lv.x = this.sp.x * this.speed;
            // this.node.x += this.sp.x * this.speed * dt;
        } else {
            this.lv.x = 0;
        }
        if (this.sp.y != 0) {
            this.lv.y = this.sp.y * this.speed;
            // this.node.y += this.sp.y * this.speed * dt;
        } else {
            this.lv.y = 0;
        }
        this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;
    }
}
